package com.midele.goodstuff.data.repository.net_util

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.Response

/**
 * 将Response转换为Flow
 */
fun <T> Response<T>.toFlow(): Flow<NetworkResult<T>> = flow {
    emit(NetworkResult.Loading())
    try {
        if (isSuccessful) {
            body()?.let {
                emit(NetworkResult.Success(it))
            } ?: emit(NetworkResult.Error(code(), "Response body is null"))
        } else {
            emit(NetworkResult.Error(code(), message()))
        }
    } catch (e: Exception) {
        emit(NetworkResult.Error(500, e.message ?: "Unknown error"))
    }
}

/**
 * 将ApiResponse转换为Flow
 */
fun <T> Response<ApiResponse<T>>.toApiFlow(): Flow<NetworkResult<T>> = flow {
    emit(NetworkResult.Loading())
    try {
        if (isSuccessful) {
            body()?.let { response ->
                if (response.code == 200) {
                    response.data?.let {
                        emit(NetworkResult.Success(it))
                    } ?: emit(NetworkResult.Error(response.code, "Response data is null"))
                } else {
                    emit(NetworkResult.Error(response.code, response.message))
                }
            } ?: emit(NetworkResult.Error(code(), "Response body is null"))
        } else {
            emit(NetworkResult.Error(code(), message()))
        }
    } catch (e: Exception) {
        emit(NetworkResult.Error(500, e.message ?: "Unknown error"))
    }
} 